//
//  ImageDetailView.swift
//  Chatup
//
//  Created by iron man on 2023/12/10.
//

import SwiftUI
import Kingfisher
import Photos


struct ImageDetailView: View {
    @State private var scale: CGFloat = 1.0
    @Binding var image: String
    @State private var showToast = false

    var body: some View {
        if image.hasPrefix("http"){
            ZStack(alignment: .bottom) {
                VStack {
                    Spacer()
                    KFImage.url(URL(string: image))
                        .cacheOriginalImage()
                        .fade(duration: 1.0)
                        .resizable()
                        .scaledToFit()
                        .gesture(MagnificationGesture()
                            .onChanged { value in
                                self.scale = value
                            }
                        )
                    Spacer()
                }
                
                VStack {
                    Spacer()
                    Button {
                        downloadAndSaveImage(from: URL(string: image)!)
                    } label: {
                        Image("icon_download")
                            .resizable()
                            .frame(width: 24,height: 24)
                    }
                }

                if showToast{
                    ToastView(text: "Success!")
                }
            }
        }else{
            Image(image)
                .resizable()
                .scaledToFit()
                .gesture(MagnificationGesture()
                    .onChanged { value in
                        self.scale = value
                    }
                )
                .scaleEffect(scale)
                .navigationBarTitle("", displayMode: .inline)
        }
    }
    func downloadAndSaveImage(from url: URL) {
        // 请求保存图片到相册的权限
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else {
                // 处理权限未被授予的情况
                return
            }

            // 使用Kingfisher下载图片
            KingfisherManager.shared.retrieveImage(with: url) { result in
                switch result {
                case .success(let value):
                    // 图片下载成功，保存到相册
                    let image = value.image
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                    showToast.toggle()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        withAnimation {
                            showToast.toggle()
                        }
                    }
                case .failure(let error):
                    // 处理图片下载失败
                    print(error)
                }
            }
        }
    }
    
    func saveLocalImage(from image: UIImage){
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else {
                // 处理权限未被授予的情况
                return
            }

            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        }
        
    }
}
#Preview {
    ImageDetailView(image: .constant(""))
}
